package com.yz.platform.modules.api.controller;

import com.google.common.base.Strings;
import com.google.gson.Gson;

import com.yz.platform.common.exception.CommonException;
import com.yz.platform.common.message.RespMsg;
import com.yz.platform.common.utils.MD5Util;
import com.yz.platform.modules.api.annotation.AuthIgnore;
import com.yz.platform.modules.api.entity.AuthEntity;
import com.yz.platform.modules.api.service.AuthService;


import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证接口 author:lin Date : 2017/10/14 上午9:17
 */
@Controller
@RequestMapping("/api")
public class AuthController {


    private Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    /**
     * 认证接口
     */
    @AuthIgnore
    @RequestMapping("/auth")
    @ResponseBody
    public RespMsg<String> auth(HttpServletRequest request) {

        String key = request.getParameter("key");
        String scriptNo = request.getParameter("scriptNo");
        String deviceNo = request.getParameter("deviceNo");
        String packageName = request.getParameter("packageName");
        String accessToken = request.getHeader("accessToken");

        if (Strings.isNullOrEmpty(key)) {
            return RespMsg.fail("激活码不能为空");
        }


        boolean authFail = Strings.isNullOrEmpty(scriptNo)
                || Strings.isNullOrEmpty(deviceNo)
                || Strings.isNullOrEmpty(packageName)
                || Strings.isNullOrEmpty(accessToken);

        String md5 = MD5Util.MD5(scriptNo + packageName);

        if (authFail || !md5.equalsIgnoreCase(accessToken)) {
            return RespMsg.fail("脚本认证失败");
        }

        AuthEntity authEntity = new AuthEntity();
        authEntity.setScriptNo(scriptNo);
        authEntity.setPkgName(packageName);
        authEntity.setToken(accessToken);
        authEntity.setKey(key);
        authEntity.setDeviceNo(deviceNo);

        log.info(" auth >>> " + new Gson().toJson(authEntity));

        boolean result = false;
        try {
            result = authService.checkAuth(authEntity);
        } catch (CommonException e) {
            return RespMsg.fail(e.getMsg());
        }
        if (result) {
            return RespMsg.success("ok");
        } else {
            return RespMsg.fail("fail");
        }

    }


}
